use argh::FromArgs;

use aspect_core::datadir;

use crate::context;
use crate::errors::Error;

#[derive(Debug, PartialEq, FromArgs)]
#[argh(
    subcommand,
    name = "update",
    description = "updates an existing device identity"
)]
pub struct Args {
    #[argh(positional, description = "update comment")]
    comment: String,
}

pub fn exec(args: Args, ctx: context::Context) -> Result<(), Error> {
    let mut dd = datadir::Datadir::open(ctx.datadir)?;

    let mut signer = dd.load_device_auth()?;
    let ident = *signer.last_update().ident();
    let new_pkg = signer.create_update(args.comment);

    let dp_buf = aspect_codec::encode_to_vec(&new_pkg)?;
    let dp_hex = hex::encode(dp_buf);

    dd.save_device_auth(&signer)?;
    eprintln!("saved signer");
    println!("ident {ident}");
    println!("dirpackage {dp_hex}");
    Ok(())
}
